import { ref } from "vue";
import { defineStore } from "pinia";
import type { Ref } from "vue";
import type { PartialSearchDTO, SearchGoodVO } from "@/types/searchType";
import type { GuessItemVO } from "@/types/homeType";
import { searchGoodsAPI } from "@/api/searchHistoryAPI";

const useSearchHistoryStore = defineStore("searchHistoryStore", () => {
   // 搜索关键字列表
   const historyList: Ref<string[]> = ref<string[]>([]);
   // 搜索的商品列表
   const goodList: Ref<GuessItemVO[]> = ref<GuessItemVO[]>([]);
   // 搜索的商品总数
   const total: Ref<number> = ref<number>(1);
   // push关键字的回调函数
   const pushKeyword = (keyword: string): void => {
      const index = historyList.value.findIndex(item => item === keyword);
      if (index !== -1) {
         historyList.value.splice(index, 1);
      }
      historyList.value.unshift(keyword);
   };
   //清空关键字的回调函数
   const clearKeyword = () => {
      historyList.value = [];
   };
   // 发送请求搜索商品的回调函数
   const searchGoods = async (searchParams: PartialSearchDTO): Promise<void> => {
      try {
         if (goodList.value.length >= total.value) {
            await uni.showToast({ title: "数据加载完毕", icon: "success" });
            return;
         } else {
            const { result }: { result: SearchGoodVO } = await searchGoodsAPI(searchParams);
            goodList.value.push(...result.pageData.items);
            total.value = result.pageData.counts;
         }

      } catch (error: any) {
         await error;
      }
   };
   return {
      historyList,
      pushKeyword,
      clearKeyword,
      goodList,
      searchGoods,
   };
}, {
   persist: {
      key: "historyList",
      paths: ["historyList"],
      storage: {
         getItem(key) {
            return uni.getStorageSync(key);
         },
         setItem(key, value) {
            uni.setStorageSync(key, value);
         },
      },
   },
});


export default useSearchHistoryStore;